import { chromium } from 'playwright';
import tools from './toolsSpecification/toolsSpecification.json' with {type: 'json'} ;
import { clickingTools } from './clickingTools/clickingTools.js' ;
import { filterTools } from './filterTools/filterTools.js' ;
import { highlightsTools } from './highlightsTools/highlightsTools.js' ;
import { navigationTools } from './navigationTools/navigationTools.js' ;
import { scrapingTools } from './scrapingTools/scrapingTools.js' ;
import { tabHandlingTools } from './tabHandlingTools/tabHandlingTools.js' ;
import { visionTools } from './visionTools/visionTools.js' ;
import { uploadFileTools } from './uploadFileTools/uploadFileTools.js';
import {browserManagerUtils} from './browserManagerUtils.js' ;


export class browserManager
{
    static #tools = tools ;

    static async create()
    {
        const cdpUrl = await browserManagerUtils.getCDPUrl(); // Chrome must be running with CDP enabled
        console.error(cdpUrl) ;
        const browser = await chromium.connectOverCDP(cdpUrl);
        const context = browser.contexts()[0] || await browser.newContext({ viewport: null });
        const page = await context.newPage();

        await page.goto("https://www.google.com/");
        const pageRef = {ref: page} ;
        return new browserManager(browser, pageRef, context);
    }

    static async createWithoutCdp()
    {
        const browser = await chromium.launch({headless: false,args: ['--start-fullscreen']}) ;
        const context = await browser.newContext({viewport: null});
        const page = await context.newPage() ;
        const pageRef = {ref: page} ;
        await page.goto("https://duckduckgo.com/");

        return new browserManager(browser, pageRef, context);
    }

    constructor(browser, pageRef, context)
    {
        this.browser = browser;
        this.pageRef = pageRef;
        this.navigationTools = new navigationTools(pageRef) ;
        this.highlightsTools = new highlightsTools(pageRef) ;
        this.filterTools = new filterTools(pageRef) ;
        this.scrapingTools = new scrapingTools(pageRef,this.filterTools,this.highlightsTools) ;
        this.tabHandlingTools = new tabHandlingTools(pageRef,context) ;
        this.visionTools = new visionTools(pageRef,this.scrapingTools) ;
        this.uploadFileTools = new uploadFileTools(pageRef) ;
        this.clickingTools = new clickingTools(pageRef,this.scrapingTools,this.tabHandlingTools,this.highlightsTools) ;
        this.browserManager = this;
    }

    async close()
    {
        // Close context
        if (this.pageRef.ref) {
            await this.pageRef.ref.close();
            console.error("page closed.");
        }

    }

    getTools()
    {
        const currentToolsList = browserManager.#tools.map(tool =>(
        {
            ...tool,
            functionRef: this[tool.className][tool.name].bind(this[tool.className]),
        })) ;
        return currentToolsList ;
    }
}
